2 // ShareTableViewDataSource.swift
5 // Created by Claudio Cambra on 27/2/24.
11 import NextcloudFileProviderKit
12 import NextcloudCapabilitiesKit
15 class ShareTableViewDataSource: NSObject, NSTableViewDataSource, NSTableViewDelegate {
16 private let shareItemViewIdentifier = NSUserInterfaceItemIdentifier("ShareTableItemView")
17 private let shareItemViewNib = NSNib(nibNamed: "ShareTableItemView", bundle: nil)
18 private let reattemptInterval: TimeInterval = 3.0
20 let kit = NextcloudKit.shared
22 var uiDelegate: ShareViewDataSourceUIDelegate?
23 var sharesTableView: NSTableView? {
25 sharesTableView?.register(shareItemViewNib, forIdentifier: shareItemViewIdentifier)
26 sharesTableView?.rowHeight = 42.0 // Height of view in ShareTableItemView XIB
27 sharesTableView?.dataSource = self
28 sharesTableView?.delegate = self
29 sharesTableView?.reloadData()
32 var capabilities: Capabilities?
33 var itemMetadata: NKFile?
35 private(set) var itemURL: URL?
36 private(set) var itemServerRelativePath: String?
37 private(set) var shares: [NKShare] = [] {
38 didSet { Task { @MainActor in sharesTableView?.reloadData() } }
40 private(set) var account: Account? {
42 guard let account = account else { return }
44 account: account.ncKitAccount,
45 urlBase: account.serverUrl,
46 user: account.username,
47 userId: account.username,
48 password: account.password,
49 userAgent: "Nextcloud-macOS/FileProviderUIExt",
56 func loadItem(url: URL) {
57 itemServerRelativePath = nil
65 DispatchQueue.main.async {
66 Timer.scheduledTimer(withTimeInterval: self.reattemptInterval, repeats: false) { _ in
67 Task { await self.reload() }
73 guard let itemURL else {
74 presentError("No item URL, cannot reload data!")
77 guard let itemIdentifier = await withCheckedContinuation({
78 (continuation: CheckedContinuation<NSFileProviderItemIdentifier?, Never>) -> Void in
79 NSFileProviderManager.getIdentifierForUserVisibleFile(
81 ) { identifier, domainIdentifier, error in
82 defer { continuation.resume(returning: identifier) }
83 guard error == nil else {
84 self.presentError("No item with identifier: \(error.debugDescription)")
89 presentError("Could not get identifier for item, no shares can be acquired.")
94 let connection = try await serviceConnection(url: itemURL, interruptionHandler: {
95 Logger.sharesDataSource.error("Service connection interrupted")
97 guard let serverPath = await connection.itemServerPath(identifier: itemIdentifier),
98 let credentials = await connection.credentials() as? Dictionary<String, String>,
99 let convertedAccount = Account(dictionary: credentials),
100 !convertedAccount.password.isEmpty
102 presentError("Failed to get details from File Provider Extension. Retrying.")
106 let serverPathString = serverPath as String
107 itemServerRelativePath = serverPathString
108 account = convertedAccount
109 await sharesTableView?.deselectAll(self)
110 capabilities = await fetchCapabilities()
111 guard capabilities != nil else { return }
112 guard capabilities?.filesSharing?.apiEnabled == true else {
113 presentError("Server does not support shares.")
116 guard let account else {
117 presentError("Account data is unavailable, cannot reload data!")
120 itemMetadata = await fetchItemMetadata(
121 itemRelativePath: serverPathString, account: account, kit: kit
123 guard itemMetadata?.permissions.contains("R") == true else {
124 presentError("This file cannot be shared.")
127 shares = await fetch(
128 itemIdentifier: itemIdentifier, itemRelativePath: serverPathString
131 presentError("Could not reload data: \(error), will try again.")
137 itemIdentifier: NSFileProviderItemIdentifier, itemRelativePath: String
138 ) async -> [NKShare] {
139 Task { @MainActor in uiDelegate?.fetchStarted() }
140 defer { Task { @MainActor in uiDelegate?.fetchFinished() } }
142 let rawIdentifier = itemIdentifier.rawValue
143 Logger.sharesDataSource.info("Fetching shares for item \(rawIdentifier, privacy: .public)")
145 guard let account else {
146 self.presentError("NextcloudKit instance or account is unavailable, cannot fetch shares!")
150 let parameter = NKShareParameter(path: itemRelativePath)
152 return await withCheckedContinuation { continuation in
154 parameters: parameter, account: account.ncKitAccount
155 ) { account, shares, data, error in
156 let shareCount = shares?.count ?? 0
157 Logger.sharesDataSource.info("Received \(shareCount, privacy: .public) shares")
158 defer { continuation.resume(returning: shares ?? []) }
159 guard error == .success else {
160 self.presentError("Error fetching shares: \(error.errorDescription)")
167 private func fetchCapabilities() async -> Capabilities? {
168 guard let account else {
169 self.presentError("Could not fetch capabilities as account is invalid.")
173 return await withCheckedContinuation { continuation in
174 kit.getCapabilities(account: account.ncKitAccount) { account, data, error in
175 guard error == .success, let capabilitiesJson = data?.data else {
176 self.presentError("Error getting server caps: \(error.errorDescription)")
177 continuation.resume(returning: nil)
180 Logger.sharesDataSource.info("Successfully retrieved server share capabilities")
181 continuation.resume(returning: Capabilities(data: capabilitiesJson))
186 private func presentError(_ errorString: String) {
187 Logger.sharesDataSource.error("\(errorString, privacy: .public)")
188 Task { @MainActor in self.uiDelegate?.showError(errorString) }
191 // MARK: - NSTableViewDataSource protocol methods
193 @objc func numberOfRows(in tableView: NSTableView) -> Int {
197 // MARK: - NSTableViewDelegate protocol methods
199 @objc func tableView(
200 _ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int
202 let share = shares[row]
203 guard let view = tableView.makeView(
204 withIdentifier: shareItemViewIdentifier, owner: self
205 ) as? ShareTableItemView else {
206 Logger.sharesDataSource.error("Acquired item view from table is not a share item view!")
213 @objc func tableViewSelectionDidChange(_ notification: Notification) {
214 guard let selectedRow = sharesTableView?.selectedRow, selectedRow >= 0 else {
215 Task { @MainActor in uiDelegate?.hideOptions(self) }
218 let share = shares[selectedRow]
219 Task { @MainActor in uiDelegate?.showOptions(share: share) }